<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model;
use App\Base\BaseCache;
use App\Entity\Art;
use App\Base\BaseModel;
use App\Setting\ArtSetting;

class ArtModel extends BaseModel{


    public function __construct($thisGetDoctrine)
    {
        parent::__construct($thisGetDoctrine);
//        $redis = new \Redis();
//        $redis->connect('localhost', 6379);

//        $cacheDriver = new \Doctrine\Common\Cache\RedisCache();
//        $cacheDriver->setRedis($redis);
//        $cacheDriver->save('cache_id', 'my_data');


    }


    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new ArtSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /*
     * 为后台获取所有文章分类【通用模块必须开发】
     */
    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    /**
     * @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository
     */
    public function getRep()
    {
        $settings = new ArtSetting($this->getDoctrine());
        return $this->em->getRepository($settings->bundleName.":".$settings->entityName);
    }

    /**
     * @return Art[]
     */
    public function getAll()
    {
        return $this->getRep()->findBy(array(),array("id"=>"DESC"));
    }

    /**
     * @param $id
     * @return null|object|Art
     */
    public function getById($id)
    {
        return $this->getRep()->find($id);
    }

    /**
     * @return array
     */
    public function getAllArray()
    {
        $data = $this->getAll();
        $re = [];
        foreach ($data as $one) {
            $re[] = $this->toArray($one);
        }
        return $re;
    }

    /**
     * @param $id
     * @return array
     */
    public function getByIdArray($id)
    {
        $en = $this->getById($id);
        return $en?$this->toArray($en):[];
    }


    /**
     * @param $key
     * @param $val
     * @return Art
     */
    public function getByKV($key,$val)
    {
        $qb = $this->createDql();
        $qb->select("A")->from("App:Art","A");
        $qb->where("A.$key = :val")->setParameter("val",$val);
        $query = $qb->getQuery();
        $data = $query->execute();
        if ($data) {
            return $data[0];
        }else{
            return [];
        }
    }

    /**
     * @param array $arr
     * @return Art
     */
    public function getByKVs($arr =[])
    {
        $qb = $this->createDql();
        $qb->select("A")->from("App:Art","A");
        $i = 0;
        foreach ($arr as $key=>$val) {
            if ($i == 0) {
                $qb->where("A.$key = :$key")->setParameter("$key",$val);
            }else{
                $qb->andWhere("A.$key = :$key")->setParameter("$key",$val);
            }
            $i++;
        }
        $query = $qb->getQuery();
        $data = $query->execute();
        if ($data) {
            return $data[0];
        }else{
            return [];
        }
    }

    /**
     * @param $key
     * @param $val
     * @return Art[]
     */
    public function getArrayByKV($key,$val)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("A.*")->from("Art","A");
        $qb->where("A.$key = :$key")->setParameter("$key",$val)->orderBy("id","DESC");
        $data = $qb->execute()->fetchAll();
        return $data;
    }

    /**
     * @param array $arr
     * @return Art[]
     */
    public function getArrayByKVs($arr)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("A.*")->from("Art","A");
        $i = 0;
        foreach ($arr as $key=>$val) {
            if ($i == 0) {
                $qb->where("A.$key = :$key")->setParameter("$key",$val);
            }else{
                $qb->andWhere("A.$key = :$key")->setParameter("$key",$val);
            }
            $i++;
        }
        $data = $qb->execute()->fetchAll();
        return $data;
    }

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function createGetListDql($isHot = 0)
    {
        $qb = $this->createDql();
        $qb->select("A.id,A.title,A.pic,A.addtime,A.intro,A.files,B.name")
            ->from("App:Art","A")
            ->leftJoin("App:ArtCategory","B","with","A.category = B.id")
        ;
        if ($isHot) {
            $qb->addOrderBy("A.isHot","DESC")
                ->addOrderBy("A.scan","DESC")
                ->addOrderBy("A.addtime","DESC");
        }else{
            $qb->orderBy("A.isTop","DESC")
                ->addOrderBy("A.isHot","DESC")
                ->addOrderBy("A.isIndex","DESC")
                ->addOrderBy("A.addtime","DESC");
        }
        return $qb;
    }

    /**
     * @param $categoryId
     * @param int $page
     * @param int $limit
     * @param string $keywords
     * @param int $province
     * @param int $isHot
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function getListFromCategory($categoryId,$page = 0,$limit = 10,$keywords="",$province = 0,$isHot = 0)
    {
        $qb = $this->createGetListDql($isHot);
        $qb->where(
            $qb->expr()->orX(
                $qb->expr()->eq("A.category", $categoryId),
                $qb->expr()->eq("B.parent", $categoryId)
            )
        )
            ->setMaxResults($limit)
            ->setFirstResult($page*$limit);
        if ($province) {
            $qb->andWhere("A.province = $province");
        }

        if ($keywords) {
            //处理字符串
            $keywords = trim($keywords);
            $keyArray = mb_split("\s",$keywords);
            $cond = $qb->expr()->orX();
            foreach ($keyArray as $v) {
                $cond->add($qb->expr()->like("A.title", "'%$v%'"));
                $cond->add($qb->expr()->like("A.content", "'%$v%'"));
                $cond->add($qb->expr()->like("A.intro", "'%$v%'"));
            }
            $qb->andWhere($cond);
        }
        return $qb;
    }

    /**
     * @param $categoryId
     * @param $keywords
     * @return int
     */
    public function getListCountFromCategory($categoryId,$keywords="")
    {
        $qb = $this->createGetListDql();
        $qb->where(
            $qb->expr()->orX(
                $qb->expr()->eq("A.category", $categoryId),
                $qb->expr()->eq("B.parent", $categoryId)
            )
        );

        if ($keywords) {
            //处理字符串
            $keywords = trim($keywords);
            $keyArray = mb_split("\s",$keywords);
            $cond = $qb->expr()->orX();
            foreach ($keyArray as $v) {
                $cond->add($qb->expr()->like("A.title", "'%$v%'"));
                $cond->add($qb->expr()->like("A.content", "'%$v%'"));
                $cond->add($qb->expr()->like("A.intro", "'%$v%'"));
            }
            $qb->andWhere($cond);
        }
        $qb->select("count(A.id) as num");
        $data = $qb->getQuery()->execute();
        return $data[0]["num"];
    }

    public function getIndexList($categoryId,$page = 0,$limit = 10,$province = 0,$isHot=0)
    {
//        var_dump(1);
//        $config = new \Doctrine\ORM\Configuration();
//        $config->setQueryCacheImpl(new \Doctrine\Common\Cache\RedisCache());
        $qb = $this->getListFromCategory($categoryId,$page,$limit,"",$province,$isHot );
        $rst = $qb->getQuery()->useQueryCache(true)->execute();
        return $rst;
    }


    public function getCatListData($category,$page = 0,$limit = 10,$keywords="")
    {
        $ArtCategoryModel = new ArtCategoryModel($this->getDoctrine());
        $thisCat = $ArtCategoryModel->getById($category);
        $parentCat = $thisCat;
        $curId = 0;
        $curCat = "全部";
        if ($thisCat->getLevel() == 2) {
            //获取父级分类
            $parentCatId = $thisCat->getParent();
            $parentCat = $ArtCategoryModel->getById($parentCatId);
            $curId = $category;
            $curCat = $thisCat->getName();
        }else{
            $parentCatId =  $category;
        }
        $sonCat = $ArtCategoryModel->getSons($parentCatId);

        //list

        $countData = $this->getListCountFromCategory($category,$keywords);

        $artList = $this->getListFromCategory($category,$page,$limit,$keywords)->getQuery()->execute();
        $data["parentCat"] = $parentCat;
        $data["sonCat"] = $sonCat;
        $data["list"] = $artList;
        $data["curId"] = $curId;
        $data["curCat"] = $curCat;
        $data["total"] = $countData;

        return $data;
    }
}